const {
  Builder,
  By,
  Key,
  until
} = require('selenium-webdriver');
const fs = require('fs');
const api = require('./sendMsg');

function getTime() {
  let date = new Date();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hours = date.getHours();
  let minute = date.getMinutes();
  let seconds = date.getSeconds();
  return `${month}月${day}日${hours}时${minute}分${seconds}秒`
}

let nozomi = {
  id: 学号,
  pw: 密码,
  qq: qq号
}


async function example(params) {
  let driver = await new Builder().forBrowser('chrome').build();
  async function open() {
    await driver.get('https://stuhealth.jnu.edu.cn/#/login');
    await driver.findElement({
      xpath: '//*[@id="zh"]'
    }).sendKeys(`${params.id}`);
    await driver.findElement({
      xpath: '//*[@id="passw"]'
    }).sendKeys(`${params.pw}`, Key.RETURN);
    await driver.sleep(1000);
  }

  // 打卡
  try {
    await driver.get('https://stuhealth.jnu.edu.cn/#/login');
    await driver.findElement({
      xpath: '//*[@id="zh"]'
    }).sendKeys(`${params.id}`);
    await driver.findElement({
      xpath: '//*[@id="passw"]'
    }).sendKeys(`${params.pw}`, Key.RETURN);
    await driver.sleep(5000);
    try {
      await driver.findElement({
        xpath: '//*[@id="10000"]'
      }).click();
      await driver.findElement({
        xpath: '//*[@id="tj"]'
      }).click();
      console.log("打卡成功");
    } catch {
      console.log("已打卡");
    } finally {
      // await driver.navigate().refresh();
      await open();
      // await driver.navigate().to('https://www.baidu.com')
      await driver.sleep(1000);

      // 截图
      let imgBase = await driver.takeScreenshot();

      //图片
      let dataBuffer = Buffer.from(imgBase, 'base64');

      let imgName = `${getTime()}.png`;
      fs.writeFileSync(`./img/${imgName}`, dataBuffer);

      // 发送
      
      try{
        api.sendToPerson({
          id: params.qq,
          msg: `[CQ:image,file=file://127.0.0.1/C:/Users/Administrator/Desktop/selenium/img/${imgName}]\n\n成功打卡\n\n打卡时间为：${getTime()}`
        });
      }catch{
        api.sendToPerson({
          id: params.qq,
          msg: `打卡失败\n\n打卡失败时间为：${getTime()}`
        });
      }      

      setTimeout(() => {
        // 删除
        fs.unlink(`./img/${imgName}`, (err) => {
          if (err) {
            console.log(err);
          } else {
            console.log('删除成功');
          }
        })
      }, 5000)
    }

  } catch(err) {
    console.log(err);
  } finally {
    await driver.quit();
  }
};

async function test() {
  await example(nozomi);
  await example(aki);
}
test();
setInterval(async ()=>{
  let date = new Date();
  let hours = date.getHours();
  if (hours==0) {
    await example(nozomi);
    await example(aki);
  }  
},3600000);